<template>
  <div
    v-drag="{
      onEnd: dragEnd,
    }"
    ref="direcitveDragRef"
    class="drag"
  >
    drag directive 实现方式, 拽我
  </div>
  <div ref="vueuseDraggbleRef" class="drag blue" :style="style">
    vueuse实现方式 拽我 我正在被拽： {{ isDragging }} x: {{ toolPosition.x }} y:
    {{ toolPosition.y }}
  </div>
</template>
<script setup>
import { useLocalStorage, get } from "@vueuse/core";
import { useDraggable } from "@/useHooks";
import { onMounted, ref } from "vue";

const direcitveDragRef = ref(null);
const vueuseDraggbleRef = ref(null);
const toolPosition = useLocalStorage("toolPosition", {});
const getToolPosition = get(toolPosition); // 获取工具的位置缓存
const defaultPosition = getToolPosition?.x
  ? getToolPosition
  : {
      x: 100,
      y: 200,
    };

onMounted(() => {
  const position = localStorage.position;
  if (position) {
    const list = position.split(",");
    console.log(list);
    direcitveDragRef.value.style["top"] = list[0];
    direcitveDragRef.value.style["left"] = list[1];
  } else {
    direcitveDragRef.value.style["top"] = "300px";
    direcitveDragRef.value.style["left"] = "200px";
  }
});

const dragEnd = position => {
  console.log("----", position);
};
const { isDragging, style } = useDraggable(vueuseDraggbleRef, {
  initialValue: defaultPosition,
  preventDefault: true,
  onEnd: position => {
    for (let key in position) {
      if (position.hasOwnProperty(key)) {
        position[key] = Math.floor(position[key]);
      }
    }
    // 存储坐标到localStorage
    toolPosition.value = position;
  },
});
</script>
<style>
.drag {
  position: fixed;
  padding: 10px 20px;
  background: red;
  color: #fff;
  border-radius: 10px;
  z-index: 10;
}
.drag.blue {
  background: blue;
}
</style>
